package com.yiqi.lottery.feature.find.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.alibaba.fastjson.JSON;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.*;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.NetUtil;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.suozhang.framework.widget.PowerfulEditText;
import com.yiqi.lottery.R;
import com.yiqi.lottery.common.widget.util.FullyGridLayoutManager;
import com.yiqi.lottery.entity.bo.TokenBo;
import com.yiqi.lottery.entity.bo.UploadBo;
import com.yiqi.lottery.feature.find.contract.WriteCircleContract;
import com.yiqi.lottery.feature.find.dependencies.post.DaggerPostCircleComponent;
import com.yiqi.lottery.feature.find.dependencies.post.PostCirclePresenterModule;
import com.yiqi.lottery.feature.find.view.adapter.GridImageAdapter;
import org.json.JSONObject;

import javax.inject.Inject;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class WriteCircleActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener, WriteCircleContract.View {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.recycler)
    RecyclerView mRvImg;
    @BindView(R.id.edt_circle_write_content)
    PowerfulEditText mEdtCircleWriteContent;
    private GridImageAdapter adapter;
    private int themeId;

    private int maxSelectNum =8;// 图片最大可选数量
    private List<LocalMedia> selectList = new ArrayList<>();
    List<File> mFiles = null;
    String token = "";
    private List<UploadBo> mUploadBos;
    @Inject
    WriteCircleContract.Presenter mPresenter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_share_circle;
    }

    @Override
    protected void initInjector() {
        DaggerPostCircleComponent.builder().postCirclePresenterModule(new PostCirclePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_find_circle_write);
        initToolBar(mToolbar, "晒单圈", true, true);
        mToolbar.setOnMenuItemClickListener(this);
    }


    @Override
    protected void onStart() {
        super.onStart();
        mPresenter.postQiniuToken();
    }

    @Override
    protected void initData() {
        initImgSelector();
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_cieclr_write:
                if (TextUtils.isEmpty(mEdtCircleWriteContent.getText().toString())){
                    T.showShort("请输入内容！");
                }
                  else {
                    if (selectList != null && selectList.size() > 0){
                        initUp();
                    }else {
                        mPresenter.postCircle(mEdtCircleWriteContent.getText().toString(), null);
                    }

                }
                break;
        }
        return true;
    }

    private void initImgSelector() {
        themeId = R.style.picture_default_style1;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRvImg.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRvImg.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    int mediaType = 1;
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            PictureSelector.create(WriteCircleActivity.this).externalPicturePreview(position, selectList);
                            break;

                    }
                }
            }
        });

    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(WriteCircleActivity.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .isGif(false)// 是否显示gif图片 true or false
                    .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list
                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                adapter.setList(selectList);
                adapter.notifyDataSetChanged();
                 Logger.e("onActivityResult:"+ selectList.size());

                break;
        }
    }

    @Override
    public void showQiniuTokenSuccess(TokenBo data) {
        token = data.getToken();
    }

    @Override
    public void showQiniuTokenError(String error) {
        T.showShort(error);
    }

    @Override
    public void showUploadSuccess(String data) {
        T.showShort("上传成功");
        finish();
    }

    @Override
    public void showUploadError(String error) {
           T.showShort(error);

           mUploadBos=null;
    }
 /***
  * 上传图片至七牛云
  * */
    private void upload(File file,int pos) {
        Configuration config = new Configuration.Builder()
                .zone(FixedZone.zone2)
                .build();

        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        UploadManager  uploadManager = new UploadManager(config);
        new Thread(new Runnable() {
            @Override
            public void run() {
                uploadManager.put(file, file.getName(), token,
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                if (info.isOK()) {
                                    UploadBo uploadBo = JSON.parseObject(res.toString(), UploadBo.class);
                                    mUploadBos.add(uploadBo);
                                    if (mFiles.size()==mUploadBos.size()){
                                        mPresenter.postCircle(mEdtCircleWriteContent.getText().toString(),mUploadBos);
                                    }
                                } else {
                                    Logger.e("Upload Fail");

                                    T.showShort("上传失败！");
                                }
                            }
                        },  new UploadOptions(null, null, false,
                                new UpProgressHandler(){
                                    public void progress(String key, double percent){
                                      T.showShort("正在上传中"+getTwoDecimal(percent*100)+"%");
                                    }
                                },null));
            }
        }).start();
        }

    public  void initUp() {
        mFiles=null;
        mFiles=new ArrayList<>();
        if (selectList != null && selectList.size() > 0) {
            for (LocalMedia localMedia : selectList) {
                mFiles.add(new File(localMedia.getCompressPath()));
            }

            mUploadBos=new ArrayList<>();
            for (int i = 0; i < mFiles.size(); i++) {
                upload(mFiles.get(i),i);
            }
        }

    }

    /**
     * 将数据保留两位小数
     */
    private double getTwoDecimal(double num) {
        DecimalFormat dFormat=new DecimalFormat("#.00");
        String yearString=dFormat.format(num);
        Double temp= Double.valueOf(yearString);
        return temp;
    }
}
